﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.BasicList
{
    public partial class frm_Add_Part : Form
    {
        private INISettings mySetting;
        private SqlConnection myConnection;
        private string error;

        private DataSet ds;
        private DataViewManager dsView;

        public frm_Add_Part()
        {
            InitializeComponent();

            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);
            this.error = null;
            this.ds = new DataSet("IQ");

            LoadCustomer();
            LoadMaker();
            LoadSupplier();
            LoadIQ();
            LoadUnit();
            LoadPartClass();
            LoadCountry();
        }

        ////////////////////////////////////
        /// Load Customer List
        ///////////////////////////////////
        private void LoadCustomer()
        { 
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT CustomerID, FullName FROM [222_Customer]";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["CustomerID"].ToString() + " | " + dataReader["FullName"].ToString();
                    item.Value = dataReader["CustomerID"].ToString();
                    this.customerID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot load Customer List");
            }             
        }

        ////////////////////////////////////
        /// Load Maker List
        ///////////////////////////////////
        private void LoadMaker()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT MakerID, EnglishName FROM [222_Maker]";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["MakerID"].ToString() + " | " + dataReader["EnglishName"].ToString();
                    item.Value = dataReader["MakerID"].ToString();
                    this.makerID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot load Maker List");
            }
        }

        ////////////////////////////////////
        /// Load Supplier List
        ///////////////////////////////////
        private void LoadSupplier()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT SupplierID, SupplierName FROM [222_Supplier]";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["SupplierID"].ToString() + " | " + dataReader["SupplierName"].ToString();
                    item.Value = dataReader["SupplierID"].ToString();
                    this.supplierID.Properties.Items.Add(item);
                    this.secondSupplier.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot load Supplier List");
            }
        }

        ////////////////////////////////////
        /// Load IQ List
        ///////////////////////////////////
        private void LoadIQ()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT IQID, UnitID FROM [222_IQ]";
                SqlDataAdapter da1 = new SqlDataAdapter();
                da1.SelectCommand = cmd_sql;
                da1.TableMappings.Add("Table", "IQ");
                da1.Fill(ds);
                dsView = ds.DefaultViewManager;
                cmd_sql.Dispose();
                myConnection.Close();

                this.iqID.DataSource = dsView;
                this.iqID.DisplayMember = "IQ.IQID";
                this.iqID.ValueMember = "IQ.IQID";
                this.iqID.AutoCompleteSource = AutoCompleteSource.ListItems;

                this.iqUnit.DataBindings.Add("Text", dsView, "IQ.UnitID");
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot load IQ List");
            }
        }

        ////////////////////////////////////
        /// Load Unit List
        ///////////////////////////////////
        private void LoadUnit()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT UnitID, UnitNameEN FROM [222_Unit]";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["UnitNameEN"].ToString();
                    item.Value = dataReader["UnitID"].ToString();
                    this.buyingUnit.Properties.Items.Add(item);
                    this.usingUnit.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot load Unit List");
            }
        }

        ////////////////////////////////////
        /// Load Part Class
        ///////////////////////////////////
        private void LoadPartClass()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT ClassID, ClassName FROM [222_PartClass]";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["ClassName"].ToString();
                    item.Value = dataReader["ClassID"].ToString();
                    this.buyingUnit.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot load Class List");
            }
        }
        
        ///////////////////////////////////
        /// Load Country List
        //////////////////////////////////
        private void LoadCountry()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT CountryCode, CountryName FROM [222_Country]";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["CountryName"].ToString();
                    item.Value = dataReader["CountryCode"].ToString();
                    this.originalCountry.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot load Country List");
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }
        
        private void buttonAdd_Click(object sender, EventArgs e)
        { 
            error = null;
            string part_no = null;
            string part_purchase = null;
            string part_name = null;
            string vietnam_name = null;
            string customer = null;
            string maker = null;
            string supplier = null;
            string second_supplier = null;
            string iq_id = null;

            string buying_unit = null;
            string using_unit = null;
            string buying_exchange = null;
            string using_exchange = null;

            float exchange = 0;
            string lead_time = null;
            int leadtime = 0;
            string min_quantity = null;
            int min_qty = 0;
            string material = null;
            string part_size = null;
            float weight = 0;
            string part_weight = null;
            int export = 0;
            int rohs = 0;
            int qtybaseprice = 0;
            string safe_quantity = null;
            int safeqty = 0;
            string part_type = null;
            string classid = null;
            string packing_note = null;
            string original_country = null;
            string marume = null;
            int mar = 0;
            string department = null;
            string remark = null;

            ComboboxItem item = new ComboboxItem();

            if (string.IsNullOrEmpty(this.partNo.Text))
            {
                error = "Please enter Part No";
            }
            else
            {
                part_no = this.partNo.Text;
            }

            if (string.IsNullOrEmpty(error))
            {
                part_purchase = this.partPurchase.Text;
                part_name = this.partName.Text;
                vietnam_name = vietnamName.Text;
                if (this.customerID.SelectedIndex >= 0)
                {
                    item = (ComboboxItem)this.customerID.SelectedItem;
                    customer = item.Value.ToString();
                }
                else
                {
                    customer = "N99999";
                }
                if (this.makerID.SelectedIndex >= 0)
                {
                    item = (ComboboxItem)this.makerID.SelectedItem;
                    maker = item.Value.ToString();
                }
                else
                {
                    maker = "E00000";
                }

                if (this.supplierID.SelectedIndex >= 0)
                {
                    item = (ComboboxItem)this.supplierID.SelectedItem;
                    supplier = item.Value.ToString();
                }
                else
                {
                    supplier = "B99999";
                }

                if (this.secondSupplier.SelectedIndex >= 0)
                {
                    item = (ComboboxItem)this.secondSupplier.SelectedItem;
                    second_supplier = item.Value.ToString();
                }
                else
                {
                    second_supplier = "B99999";
                }

                if (this.iqID.SelectedIndex >= 0)
                {                    
                    iq_id = this.iqID.Text.Trim();
                }
                else
                {
                    error = "Please select IQ ID";
                }
            }
            
            if (string.IsNullOrEmpty(error))
            {
                if (this.buyingUnit.SelectedIndex >= 0)
                {
                    item = (ComboboxItem)this.buyingUnit.SelectedItem;
                    buying_unit = item.Value.ToString();
                }
                else
                {
                    buying_unit = "No";
                }

                if (!string.IsNullOrEmpty(this.buyingExchange.Text))
                {
                    if (float.TryParse(this.buyingExchange.Text, out exchange))
                    {
                        buying_exchange = this.buyingExchange.Text;
                    }
                    else
                    {
                        error = "Invalid Buying Exchange";
                    }
                }
                else
                {
                    buying_exchange = "NULL";
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (this.usingUnit.SelectedIndex >= 0)
                {
                    item = (ComboboxItem)this.usingUnit.SelectedItem;
                    using_unit = item.Value.ToString();
                }
                else
                {
                    using_unit = "No";
                }

                if (!string.IsNullOrEmpty(this.usingExchange.Text))
                {
                    if (float.TryParse(this.usingExchange.Text, out exchange))
                    {
                        using_exchange = this.usingExchange.Text;
                    }
                    else
                    {
                        error = "Invalid Using Exchange";
                    }
                }
                else
                {
                    using_exchange = "NULL";
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (!string.IsNullOrEmpty(this.leadTime.Text))
                {
                    if (Int32.TryParse(this.leadTime.Text, out leadtime))
                    {
                        lead_time = this.leadTime.Text;
                    }
                    else
                    {
                        error = "Invalid Lead Time";
                    }
                }
                else
                {
                    lead_time = "NULL";
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (!string.IsNullOrEmpty(this.minQuantity.Text))
                {
                    if (Int32.TryParse(this.minQuantity.Text, out min_qty))
                    {
                        min_quantity = this.minQuantity.Text;
                    }
                    else
                    {
                        error = "Invalid Min Quantity";
                    }
                }
                else
                {
                    min_quantity = "NULL";
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                material = this.materialValue.Text;
                part_size = this.partSize.Text;

                if (!string.IsNullOrEmpty(this.weightValue.Text))
                {
                    if (float.TryParse(this.weightValue.Text, out weight))
                    {
                        part_weight = this.weightValue.Text;
                    }
                    else
                    {
                        error = "Invalid Weight";
                    }
                }
                else
                {
                    part_weight = "NULL";
                }
            }
            if (string.IsNullOrEmpty(error))
            {
                if (this.exportCheck.Checked)
                {
                    export = 1;
                }
                else
                {
                    export = 0;
                }

                if (this.roHS.Checked)
                {
                    rohs = 1;
                }
                else
                {
                    rohs = 0;
                }

                if (this.quantityBasePrice.Checked)
                {
                    qtybaseprice = 1;
                }
                else
                {
                    qtybaseprice = 0;
                }

                if (!string.IsNullOrEmpty(this.safeQuantity.Text))
                {
                    if (Int32.TryParse(this.safeQuantity.Text, out safeqty))
                    {
                        safe_quantity = this.safeQuantity.Text;
                    }
                    else
                    {
                        error = "Invalid Safe Quantity";
                    }
                }
                else
                {
                    safe_quantity = "NULL";
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                part_type = this.partType.Text;
                if (this.classID.SelectedIndex >= 0)
                {
                    item = (ComboboxItem)this.classID.SelectedItem;
                    classid = item.Value.ToString();
                }
                else
                {
                    classid = "other";
                }
                
                packing_note = this.packingNote.Text;

                if (this.originalCountry.SelectedIndex >= 0)
                {
                    item = (ComboboxItem)this.originalCountry.SelectedItem;
                    original_country = item.Value.ToString();
                }
                else
                {
                    original_country = "18";
                }

                if (!string.IsNullOrEmpty(this.marumeValue.Text))
                {
                    if (Int32.TryParse(this.marumeValue.Text, out mar))
                    {
                        marume = this.marumeValue.Text;
                    }
                    else
                    {
                        error = "Invalid marume";
                    }
                }
                else
                {
                    marume = "NULL";
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                department = this.departmentValue.Text;
                remark = this.remarkValue.Text;
                try
                {
                    myConnection.Open();                    
                    string sql = "INSERT INTO [222_Part] ([PartNo], [PartNoPurchase], [PartEnglishName], [PartVietNamName],"
                        + " [CustomerID], [MakerID], [SupplierID], [SecondSupplierID], [IQID], [UsingUnit], [BuyingUnit],"
                        + " [Using/IQEx], [Buying/IQEx], [LeadTime], [MinQuantity], [ROHS], [Material], [Weight], [PartSize],"
                        + " [QuantityBasePrice], [ExportOrImport], [SafeQuantity], [PType], [Class], [PackingNote], [Remark],"
                        + " [Marume], [OCountry], [Department])"
                        + " VALUES ('" + part_no + "', '" + part_purchase + "', N'" + part_name + "', N'" + vietnam_name + "',"
                        + " '" + customer + "', '" + maker + "', '" + supplier + "', '" + second_supplier + "', '" + iq_id + "',"
                        + " '" + using_unit + "', '" + buying_unit + "', " + using_exchange + ", " + buying_exchange + ","
                        + " " + lead_time + ", " + min_quantity + ", " + rohs + ", '" + material + "', " + part_weight + ","
                        + " '" + part_size + "', " + qtybaseprice + ", " + export + ", " + safe_quantity + ", '" + part_type + "',"
                        + " '" + classid + "', '" + packing_note + "', N'" + remark + "', " + marume + ", '" + original_country + "',"
                        + " '" + department + "')";
                    
                    SqlCommand cmd_sql = new SqlCommand(sql, myConnection);                    
                    cmd_sql.ExecuteNonQuery();
                    cmd_sql.Dispose();
                    myConnection.Close();
                    MessageBox.Show("Part added success.");
                    clearForm();
                }
                catch (Exception ex)
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    MessageBox.Show(ex.Message);
                    //MessageBox.Show("Cannot add Part. Please try again.");
                }
            }
            else
            {
                MessageBox.Show(error);
            }  
        }

        private void clearForm()
        {
            foreach (Control c in this.Controls)
            {
                if (c is DevExpress.XtraEditors.TextEdit)
                {
                    ((DevExpress.XtraEditors.TextEdit)c).Text = null;
                }

                if (c is DevExpress.XtraEditors.ComboBoxEdit)
                {
                    ((DevExpress.XtraEditors.ComboBoxEdit)c).SelectedIndex = -1;
                }

                if (c is System.Windows.Forms.MaskedTextBox)
                {
                    ((System.Windows.Forms.MaskedTextBox)c).Text = null;
                }
            }
        }
    }
}
